package com.base.common.common;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;

import com.base.common.db.model.MachineCacheInfo;
import com.base.common.util.ToastAlert;
import com.base.common.util.log.CrashHandler;
import com.squareup.leakcanary.internal.ActivityLifecycleCallbacksAdapter;


/**
 * 全局Application
 */
public class CustomApplication extends Application {

    private static CustomApplication app;
    private static Context context;
    String topActivity;
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);

    }

    @Override
    public void onCreate() {
        super.onCreate();

        app = this;
        context = getApplicationContext();

        CrashHandler.init(context);
//        context.getApplicationContext().getCacheDir();

        registerLifeCycle();
        ToastAlert.init(context);

    }

    void registerLifeCycle() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacksAdapter() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                super.onActivityCreated(activity, savedInstanceState);
            }

            @Override
            public void onActivityStarted(Activity activity) {
                super.onActivityStarted(activity);
            }

            @Override
            public void onActivityResumed(Activity activity) {
                topActivity = activity.getClass().getName();
                super.onActivityResumed(activity);
            }

            @Override
            public void onActivityPaused(Activity activity) {
                super.onActivityPaused(activity);
            }

            @Override
            public void onActivityStopped(Activity activity) {
                super.onActivityStopped(activity);
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
                super.onActivitySaveInstanceState(activity, outState);
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                super.onActivityDestroyed(activity);
            }
        });
    }

    public boolean isTopActivity(String TAG) {
        if (TextUtils.isEmpty(topActivity)) return false;
        return topActivity.endsWith(TAG);
    }


    public static Context getContext() {
        return context;
    }

    public static CustomApplication getInstance() {
        return app;
    }

    @Override
    public void onTerminate() {
        MachineCacheInfo.getInstance().writeToCache();
        super.onTerminate();
    }
}
